<template>
  <div class="eleMap">
    <div id="viewDiv">
      <div style="position:absolute;top:160px;left:220px;z-index:100;" title="Draw and measure point">
        <span id="pointButton" class="action-button esri-icon-blank-map-pin esri-widget-button esri-widget esri-interactive" type="button"></span>
        <button class="action-button esri-icon-polyline" id="polylineButton" type="button"
                title="Draw polyline"></button>
        <span id="polygonButton" class="action-button esri-icon-polygon esri-widget-button esri-widget esri-interactive" type="button"></span>
        <span id="rectangleButton" class="action-button esri-icon-checkbox-unchecked esri-widget-button esri-widget esri-interactive"
              type="button"></span>
        <!--<span id="circleButton" class="action-button esri-icon-radio-unchecked esri-widget-button esri-widget esri-interactive" type="button"></span>-->
        <!--<span id="ellipseButton" class="action-button esri-icon-hollow-eye esri-widget-button esri-widget esri-interactive" type="button"></span>-->
        <!--<span id="triangleButton" class="action-button esri-icon-up-arrow esri-widget-button esri-widget esri-interactive" type="button"></span>-->
      </div>
    </div>
  </div>
</template>

<script>
  import * as esriLoader from 'esri-loader';

  export default {
    name: 'geometries',
    data () {
      return {
        view: null,
        pointGraphic: null,
        _polygon: null,
        _polyline: null,
      }
    },
    created (){
      esriLoader.loadCss(cssURL);
    },
    mounted () {
      this.createMap();
    },
    methods: {
      createMap () {
        // 引入依赖
        esriLoader.loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/layers/GraphicsLayer',
          'esri/widgets/Sketch/SketchViewModel',
          "esri/geometry/geometryEngine",
          "esri/geometry/Point",
          "esri/geometry/Polyline",
          "esri/geometry/Polygon",
          'esri/layers/TileLayer',
          "esri/Basemap",
          'esri/Graphic'
        ], {url:dojoURL}).then(([EsriMap, MapView, GraphicsLayer, SketchViewModel, geometryEngine, Point, Polyline, Polygon, TileLayer, Basemap, Graphic]) => {
          var layer = new TileLayer({
            url:mapServer
          })
          var customBasemap = new Basemap({
            baseLayers: [layer],
            title: 'geometries',
            id: 'geometries'
          })

          this.map = new EsriMap({
            basemap: customBasemap
          })


          let updateGraphic
          let tempGraphicsLayer = new GraphicsLayer()
          this.map.add(tempGraphicsLayer, 1)
          let view = new MapView({
            container: 'viewDiv',
            center: [114.21868761726246, 30.584733852070247],
            zoom: 5,
            map: this.map
          })
         let pointSymbol = { // symbol used for points
           type: 'simple-marker', // autocasts as new SimpleMarkerSymbol()
           style: 'square',
           color: '#8A2BE2',
           size: '10px',
           outline: { // autocasts as new SimpleLineSymbol()
             color: [255, 255, 255],
             width: 3 // points
           }
         }
//            let pointSymbol = {
//              type: 'picture-marker', // autocasts as new PictureMarkerSymbol()
//              url:  'static/img/location_point.png',
//              width: '40px',
//              height: '40px'
//            }

          let polylineSymbol = {
            type: 'simple-line', // autocasts as new SimpleLineSymbol()
            color: '#8A2BE2',
            width: '4',
            style: 'solid'
          }

          let polygonSymbol = { // symbol used for polygons
            type: 'simple-fill', // autocasts as new SimpleFillSymbol()
            color: 'rgba(138,43,226, 0.8)',
            style: 'solid',
            outline: {
              color: 'white',
              width: 1
            }
          }
          view.when(function (evt) {
            let sketchViewModel = new SketchViewModel({
              view: view,
              layer: tempGraphicsLayer,
              pointSymbol: pointSymbol,
              polygonSymbol: polygonSymbol
            })
//            let savePosition = document.getElementById('savePosition')
//            savePosition.addEventListener('click', function () {
//              this.s_alert('保存')
//              //console.log('savePosition')
//              //console.log(tempGraphicsLayer.graphics.items)
//            })
            setUpClickHandler()
            sketchViewModel.on('draw-complete', addGraphic)
            sketchViewModel.on('update-complete', addGraphic)
            sketchViewModel.on('update-cancel', addGraphic)
            let drawPointButton = document.getElementById('pointButton')
            let drawpolylineSymbol = document.getElementById('polylineButton')
            let drawPolygonButton = document.getElementById('polygonButton')
            let drawRectangleButton = document.getElementById('rectangleButton')
//            let drawCircleButton = document.getElementById('circleButton')
//            let drawEllipseButton = document.getElementById('ellipseButton')
//            let drawTriangleButton = document.getElementById('triangleButton')
            clickButton(drawPointButton, 'point')
            clickButton(drawpolylineSymbol, 'polyline')
            clickButton(drawPolygonButton, 'polygon')
            clickButton(drawRectangleButton, 'rectangle')
//            clickButton(drawCircleButton, 'circle')
//            clickButton(drawEllipseButton, 'ellipse')
//            clickButton(drawTriangleButton, 'triangle')
            function clickButton (button, type) {
              button.onclick = function () {
                view.graphics.removeAll();
                sketchViewModel.reset()
                tempGraphicsLayer.removeAll()
                sketchViewModel.create(type)
                setActiveButton(this)
              }
            }
            function setActiveButton (selectedButton) {
              // focus the view to activete keyboard shortcuts for sketching
              view.focus()
              let elements = document.getElementsByClassName('active')
              for (let i = 0; i < elements.length; i++) {
                elements[i].classList.remove('active')
              }
              if (selectedButton) {
                selectedButton.classList.add('active')
              }
            }
            function setUpClickHandler () {
              view.on('click', function (evt) {
                // view.hitTest(evt).then(function (response) {
                //   let results = response.results
                //   if (results.length && results[results.length - 1].graphic) {
                //     if (!updateGraphic) {
                //       updateGraphic = results[results.length - 1].graphic
                //       tempGraphicsLayer.remove(updateGraphic)
                //       sketchViewModel.update(updateGraphic.geometry)
                //     }
                //   }
                // })

                var centerPt = new Point({
                  type: "point", // autocasts as new Point()
                  longitude: evt.mapPoint.longitude,
                  latitude: evt.mapPoint.latitude
                });
                var centerPtGraphic = new Graphic({
                  geometry: centerPt,
                  symbol: pointSymbol
                })
                centerPtGraphic.attributes = {
                  'uid': centerPtGraphic.uid
                }
                var buffPoint = geometryEngine.geodesicBuffer(centerPt, 0.1, "meters");
                var buffPolyline = geometryEngine.geodesicBuffer(self._polyline, 10, "meters");
                var within = geometryEngine.within( buffPoint, buffPolyline );
                if(within){
                  view.graphics.add(centerPtGraphic);
                }
                //console.log(view.graphics.items, 'items')
                //console.log(within, 'within');
                //console.log("*******")

              })
            }
          })
          function addGraphic (evt) {
            let geometry = evt.geometry
            let symbol
            if (geometry.type === 'point') {
              symbol = pointSymbol
            } else if (geometry.type === 'polyline') {
              symbol = polylineSymbol
              self._polyline = new Polyline(geometry)
            }
            else {
              symbol = polygonSymbol
              self._polygon = new Polygon(geometry)
              self._polyline = new Polyline({
                type: "polyline",
                paths: geometry.rings
              })
            }
            var graphic = new Graphic({
              geometry: geometry,
              symbol: symbol
            })

            tempGraphicsLayer.add(graphic)


//            //console.log(tempGraphicsLayer)
            var json = graphic.toJSON();
            //console.log(JSON.stringify(json));
            updateGraphic = null
            if (geometry.type === 'polyline') {
              var lineLength = geometryEngine.geodesicLength(geometry, 'meters');
              lineLength = Math.ceil(lineLength)
              //console.log(lineLength)

              // Create a symbol for drawing the point
              var textSymbol = {
                type: "text", // autocasts as new TextSymbol()
                color: "#7A003C",
                text: lineLength + '米', //
                font: { // autocasts as new Font()
                  size: 30,
                  family: "CalciteWebCoreIcons"
                }
              };
              var lastPoint = json.geometry.paths[0][json.geometry.paths[0].length - 1];
              // First create a point geometry
              var point = new Point({
                longitude: lastPoint[0],
                latitude: lastPoint[1]
              });
              // Create a graphic and add the geometry and symbol to it
              var pointGraphic = new Graphic({
                geometry: point,
                symbol: textSymbol
              });
              // Add the graphics to the view's graphics layer
              view.graphics.add(pointGraphic);
            }
          }

        })
      }
    }
  }
</script>

<style scoped>
  .eleMap {
    width: 100%;
    height: 100%;
  }
  #viewDiv {
    width: 100%;
    height: 100%;
    z-index: -1;
  }
  .action-button {
    font-size: 16px;
    background-color: white;
    border: 1px solid #D3D3D3;
    color: #6e6e6e;
    height: 32px;
    width: 32px;
    text-align: center;
    box-shadow: 0 0 1px rgba(0, 0, 0, 0.3);
  }

  .action-button:hover,
  .action-button:focus {
    background: #0079c1;
    color: #e4e4e4;
  }
</style>
